﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using CsQuery;
using System.Threading;
using Tesseract;
using Newtonsoft.Json;

namespace Anuntiomatic
{
    public partial class FrmMain : FrmBase
    {
        int totalAds = 0;
        int totalAdsFail = 0;
        CookieCollection cookies;
        Random rand = new Random();
        DateTime Now = DateTime.Now;
        object _lock = new object(), _lock2 = new object();
        bool wait1 = false;
        string email;
        bool LicenseExpired = true;

        public FrmMain()
        {
            InitializeComponent();
            this.Load += new EventHandler(FrmMain_Load);
            this.FormClosing += new FormClosingEventHandler(UCAccount_FormClosing);
            timer2.Start();            
        }

        void FrmMain_Load(object sender, EventArgs e)
        {
            txtUserName.Enabled = false;
            txtPassword.Enabled = false;
            btnStart.Enabled = false;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker2.WorkerSupportsCancellation = true;
        }        

        void RunThread(BackgroundWorker worker)
        {
            if (!worker.IsBusy)
                worker.RunWorkerAsync();
        }

        void Login()
        {
            try
            {
                CheckLicense();
                if (!LicenseExpired)
                {
                    string u = txtUserName.Text;
                    string p = txtPassword.Text;
                    if (string.IsNullOrEmpty(u) || string.IsNullOrEmpty(p))
                    {
                        MessageBox.Show("Tên đăng nhập và mật khẩu không được bỏ trống");
                    }
                    else
                    {
                        var objs = HTMLHelper.GetURLReturnCookieAndString("http://backoffice.anuntiomatic.com/index.php", new CookieCollection());
                        cookies = (CookieCollection)objs[0];
                        objs = HTMLHelper.PostURLReturnCookieAndString("http://backoffice.anuntiomatic.com/index.php", "usuario=" + u + "&clave=" + p, cookies);
                        if (!(objs[2] as string).Equals("http://backoffice.anuntiomatic.com/boletin.php", StringComparison.OrdinalIgnoreCase))
                        {
                            MessageBox.Show("Đăng nhập không thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            btnStart.Text = "Đang chạy";
                            btnStart.Enabled = false;
                            txtUserName.Enabled = false;
                            txtPassword.Enabled = false;

                            cookies = (CookieCollection)objs[0];
                            RunThread(backgroundWorker1);
                            Thread.Sleep(1000);
                            RunThread(backgroundWorker2);

                            Now = DateTime.Now;
                            lbStartAt.Text = Now.ToString("dd/MM/yyyy HH:mm:ss");
                            timer1.Start();
                            timer3.Start();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Đã hết hạn sử dụng phần mềm. Xin mời gia hạn để tiếp tục");
                }
            }
            catch
            {
                MessageBox.Show("Có lỗi xảy ra khi đăng nhập.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        void CheckLicense()
        {
            try
            {
                LicenseInfo license = JsonConvert.DeserializeObject<LicenseInfo>(webservice.CheckLicence(email).AESDecryptString(encryptKey, iv));
                LicenseExpired = license.Expired;
            }
            catch (Exception ex)
            {
                LicenseExpired = true;
                MessageBox.Show(ex.Message);
            }
        }

        void PreRedactados(BackgroundWorker worker, string cod)
        {
            while (true)
            {
                if (!LicenseExpired)
                {
                    try
                    {
                        int timer = 0;
                        worker.ReportProgress(10, "Xem Q/C");
                        //Vào trang để nhập captcha
                        //Lock để tạo cảm giác mở từng tab trình duyệt
                        bool err = false;
                        lock (_lock)
                        {
                            var objs = HTMLHelper.GetURLReturnCookieAndString(@"http://backoffice.anuntiomatic.com/publicar.php?op=1", cookies);
                            var img = CQ.Create((string)objs[1]).Find("img[src^='captcha.php']");
                            if (img != null && img.Length > 0)
                            {
                                Image d = HTMLHelper.GetImage(string.Format(@"http://backoffice.anuntiomatic.com/captcha.php?cod={0}", cod), cookies);
                                (cod == "1" ? pic1 : pic2).Image = d;
                                worker.ReportProgress(10, "Vượt captcha");
                                string captcha = GetCaptchaFromImage(d);
                                SetText((cod == "1" ? lbCaptchaResult1 : lbCaptchaResult2), captcha);
                                if (!string.IsNullOrEmpty(captcha))
                                {
                                    HTMLHelper.PostURLReturnCookieAndString(string.Format(@"http://backoffice.anuntiomatic.com/publicacion.php?op=1&cod={0}", cod), string.Format("respuesta={0}", captcha), cookies);
                                }
                                else
                                {
                                    err = true;
                                }
                            }
                            else
                            {
                                (cod == "1" ? pic1 : pic2).Image = null;
                                SetText((cod == "1" ? lbCaptchaResult1 : lbCaptchaResult2), "");
                                err = true;
                            }
                        }
                        if (!err)
                        {
                            var obj = HTMLHelper.GetURLReturnCookieAndString(string.Format(@"http://backoffice.anuntiomatic.com/veranuncio.php?cod={0}&op=1", cod), cookies);
                            var sec = CQ.Create((string)obj[1]).Find("#segundos").Text();
                            int.TryParse(sec, out timer);
                        }
                        //Đợi xem quảng cáo
                        int waitingTime = (timer == 0 ? 60 : timer) * 10 + GetRandNext(cod);
                        if (timer > 0)
                        {
                            WaitingForAds(worker, cod, waitingTime);
                        }
                        else
                        {
                            ShowReport(worker, waitingTime, "Lỗi khi load Q/C. Đợi");
                            Interlocked.Increment(ref totalAdsFail);
                            SetText(lbTotalAds, "Tổng cộng: " + totalAds + " thành công, " + totalAdsFail + " lỗi");
                        }
                    }
                    catch (Exception)
                    {
                        SetText(lbInfo1, "ERROR");
                    }
                }
                else
                {
                    worker.ReportProgress(10, "Đã hết hạn sử dụng pm.\nXin mời gian hạn để tiếp tục");
                    (cod == "1" ? pic1 : pic2).Image = null;
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }

        void ShowReport(BackgroundWorker worker, int timer, string message)
        {
            for (int i = 0; i < timer; i++)
            {
                if (i % 10 == 0)
                    worker.ReportProgress(10, message + " trong " + ((timer - i) / 10).ToString() + "s");
                System.Threading.Thread.Sleep(100);
            }
        }

        void WaitingForAds(BackgroundWorker worker, string cod, int timer)
        {
            if (cod == "1") wait1 = true;
            ShowReport(worker, timer, "Chờ Q/C");
            if (cod == "1") wait1 = false;
            while (wait1)
                Thread.Sleep(1000);
            if (cod == "2") Thread.Sleep(1000);

            worker.ReportProgress(10, "Submit Q/C");
            var objs = HTMLHelper.GetURLReturnCookieAndString(string.Format(@"http://backoffice.anuntiomatic.com/generar.php?op=1&cod={0}", cod), cookies);
            if (objs != null)
            {
                Interlocked.Increment(ref  totalAds);
            }
            else
            {
                Interlocked.Increment(ref  totalAdsFail);
                SetText(lbInfo1, "ERROR");
            }
            SetText(lbTotalAds, "Tổng cộng: " + totalAds + " thành công, " + totalAdsFail + " lỗi");
        }

        string GetCaptchaFromImage(Image img)
        {
            try
            {
                Bitmap r = new Bitmap(img);
                for (int i = 1; i < r.Width - 1; i++)
                {
                    for (int x = 1; x < r.Height - 1; x++)
                    {
                        r.SetPixel(i, x, r.GetPixel(i, x).Name == "ff00003f" ? Color.Black : Color.White);
                    }
                }
                Pix test = PixConverter.ToPix(r.Clone(new Rectangle(20, 13, 45, 10), r.PixelFormat));

                using (var engine = new TesseractEngine(@"tessdata", @"eng", EngineMode.Default))
                {
                    using (var page = engine.Process(test, PageSegMode.SingleWord))
                    {
                        return page.GetText().Trim();
                    }
                }
            }
            catch
            {
                return string.Empty;
            }
        }

        delegate void SetTextCallback(Label blControl, string text);

        private void SetText(Label lbControl, string text)
        {
            if (lbControl.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { lbControl, text });
            }
            else
            {
                lbControl.Text = text;
            }
        }

        int _RandNext = 10;
        private int GetRandNext(string code)
        {
            _RandNext = (code == "1" ? rand.Next(10, 50) : _RandNext);
            return _RandNext;
        }

        #region events

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                PreRedactados(backgroundWorker1, "1");
            }
            catch (Exception)
            {
                lbInfo1.Text = "ERROR";
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lbInfo1.Text = e.UserState.ToString();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                lbInfo1.Text = "STOPPED";
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                PreRedactados(backgroundWorker2, "2");
            }
            catch (Exception)
            {
                lbInfo2.Text = "ERROR";
            }
        }

        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lbInfo2.Text = e.UserState.ToString();
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                lbInfo2.Text = "STOPPED";
            }
        }
       
        private void btnSubmit_Click(object sender, EventArgs e)
        {          
            Login();  
        }

        private void mnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void mnShow_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void UCAccount_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                backgroundWorker1.Dispose();
                backgroundWorker2.Dispose();
                this.Dispose();
                this.Close();
            }
            else
            {
                notifyIcon1.ShowBalloonTip(15000, "Thông báo", "Anuntiomatic vẫn đang còn chạy dưới khay hệ thống", ToolTipIcon.Info);
                this.Hide();
                e.Cancel = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan timespan = DateTime.Now - Now;
            SetText(lbTotalTime, timespan.Hours + ":" + timespan.Minutes + ":" + timespan.Seconds);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            GC.Collect();
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            CheckLicense();
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
        }

        private void linkRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://backoffice.anuntiomatic.com/registrar.php?patrocinador=giangcoi48k");
        }

        private void mnLogin_Click(object sender, EventArgs e)
        {
            FrmLogin frm = new FrmLogin();
            if (frm.ShowDialog() == DialogResult.Yes)
            {
                email = frm.Email;
                txtUserName.Text = frm.AnuntiomaticAccount;
                txtPassword.Focus();
                mnLogin.Enabled = false;
                mnPay.Enabled = true;
                mnChangePassword.Enabled = true;
                txtPassword.Enabled = true;
                btnStart.Enabled = true;
            }
        }

        private void mnPay_Click(object sender, EventArgs e)
        {
            FrmThanhToan frm = new FrmThanhToan(email);
            if (frm.ShowDialog() == DialogResult.Yes)
            {
                CheckLicense();
                MessageBox.Show(frm.Result);
            }
        }

        private void mnRegister_Click(object sender, EventArgs e)
        {
            FrmRegister frm = new FrmRegister();
            if (frm.ShowDialog() == DialogResult.Yes)
                MessageBox.Show("Đăng ký tài khoản thành công");
        }

        private void mnChangePassword_Click(object sender, EventArgs e)
        {
            FrmChangePassword frm = new FrmChangePassword(email);
            if (frm.ShowDialog() == DialogResult.Yes)
            {
                MessageBox.Show("Đổi mật khẩu thành công");
            }
        }

        private void mnAppExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn thoát chương trình?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                Application.Exit();
            }
        }
        
        #endregion events 
    }
}
